{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建一个数据集，包含2个类别共4个样本\n",
    "def createDataSet():\n",
    "    # 生成一个矩阵，每行表示一个样本\n",
    "    group = array([[1.0, 0.9], [1.0, 1.0], [0.1, 0.2], [0.0, 0.1]])\n",
    "    # 4个样本分别所属的类别\n",
    "    labels = ['A', 'A', 'B', 'B']\n",
    "    return group, labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "from numpy import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def KNNClassify(newInput, dataSet, labels, k):\n",
    "    numSamples = dataSet.shape[0]   # shape[0]表示行数\n",
    "\n",
    "    diff = tile(newInput, (numSamples, 1)) - dataSet  # 按元素求差值\n",
    "    squaredDiff = diff ** 2  # 将差值平方\n",
    "    squaredDist = sum(squaredDiff, axis = 1)   # 按行累加\n",
    "    distance = squaredDist ** 0.5  # 将差值平方和求开方，即得距离\n",
    "\n",
    "    sortedDistIndices = argsort(distance)\n",
    "    classCount = {} # define a dictionary (can be append element)\n",
    "    for i in range(k):\n",
    "        voteLabel = labels[sortedDistIndices[i]]\n",
    "        classCount[voteLabel] = classCount.get(voteLabel, 0) + 1\n",
    "\n",
    "    maxCount = 0\n",
    "    for key, value in classCount.items():\n",
    "        if value > maxCount:\n",
    "            maxCount = value\n",
    "            maxIndex = key\n",
    "\n",
    "    return maxIndex"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Your input is: [1.2 1. ] and classified to class:  A\n",
      "Your input is: [0.1 0.3] and classified to class:  B\n"
     ]
    }
   ],
   "source": [
    "dataSet, labels = createDataSet()\n",
    "testX = array([1.2, 1.0])\n",
    "k = 3\n",
    "outputLabel = KNNClassify(testX, dataSet, labels, 3)\n",
    "print(\"Your input is:\", testX, \"and classified to class: \", outputLabel)\n",
    "\n",
    "testX = array([0.1, 0.3])\n",
    "outputLabel = KNNClassify(testX, dataSet, labels, 3)\n",
    "print(\"Your input is:\", testX, \"and classified to class: \", outputLabel)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
